using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using MvcDemo02.Db;
using MvcDemo02.KeywordModel;
using MvcDemo02.Models;

namespace MvcDemo02.Controllers
{
    public class StudentController : Controller
    {
        private readonly DbSql _db;
        public StudentController()
        {
            _db = new DbSql();
        }
        public IActionResult Index()
        {
            var student = _db.student.Where(x => x.Isdel == false).ToArray();
            return View(student);
        }
        public IActionResult CreateOrEdit(int id)
        {
            var students = _db.student.Where(x => x.Id == id && x.Isdel == false).FirstOrDefault();
            return View(students);
        }
        public IActionResult Delete(int id)
        {
            var students = _db.student.Where(x => x.Id == id && x.Isdel == false).FirstOrDefault();
            students.Isdel = true;
            _db.student.Update(students);
            _db.SaveChanges();
            return RedirectToAction("index");
        }


        [HttpPost]
        public IActionResult Query(Keyword keyword)
        {
            List<Student> student;
            if (keyword.word == null)
            {
                student = _db.student.Where(x => x.Isdel == false).ToList();
            }
            else
            {
                student = _db.student.Where(x => x.Isdel == false && x.Name.Contains(keyword.word)).ToList();
            }
            return Json(student);
        }

        [HttpPost]
        public IActionResult Save(Student students)
        {
            if (students.Id <= 0)
            {
                _db.student.Add(students);
                _db.SaveChanges();
            }
            else
            {
                _db.student.Update(students);
                _db.SaveChanges();
            }
            return RedirectToAction("Index");
        }
    }
}